package my.page;

import java.util.List;

import my.dao.Dao;
import my.page.impl.PageImpl;
/**
 * 分页工厂类，该类负责创建分页对象。
 * @author 夏冬琦
 *
 */
public class PageFactory {

	private PageFactory() {}
	
	/**
	 * 根据Engine对象和PageParam对象创建Page对象。
	 * @param engine 分页引擎对象
	 * @param pageParam 分页参数对象
	 * @return
	 */
	public static  Page getPage(Engine engine,PageParam pageParam) {
		return new PageImpl(engine,pageParam);
		
	}

	
	
	/**
	 * 获取适用于MySql的分页对象
	 * @param beanClass 封装数据的JavaBean类型
	 * @param pageParam 分页参数对象
	 * @param dao Dao对象
	 * @param sql sql语句
	 * @param args sql中的占位符对应的参数
	 * @return
	 */
	public static  Page getMySqlPage(final Class<?> beanClass,PageParam pageParam,final Dao dao,final String sql,final Object... args) {
		
		Engine engine = new Engine() {

			@Override
			public int getTotal() throws Exception {
				return dao.queryInteger("select count(9) from ("+sql+") my_t_",args);
			}

			@Override
			public List<?> getData(int start, int end) throws Exception {
				String _sql=sql+" limit "+start+","+(end-start);
				return dao.queryBeanList(beanClass, _sql,args);
			}
			
		};
		
		
		return new PageImpl(engine,pageParam);
		
	}
	
	/**
	 * 获取适用于SqlServer的分页对象
	 * @param beanClass 封装数据的JavaBean类型
	 * @param pageParam 分页参数对象
	 * @param dao Dao对象
	 * @param sql sql语句
	 * @param args sql中的占位符对应的参数
	 * @return
	 */
	public static  Page getSqlServerPage(final Class<?> beanClass,PageParam pageParam,final Dao dao,final String sql,final String orderClause,final Object... args) {
		
		Engine engine = new Engine() {

			@Override
			public int getTotal() throws Exception {
				return dao.queryInteger("select count(9) from ("+sql+") my_t_",args);
			}

			@Override
			public List<?> getData(int start, int end) throws Exception {
				String _sql="select top "+(end-start)+" * from ( select row_number() over("+orderClause+") as rownumber,* from ("+sql +") t_xdq_0 ) t_xdq_1 where rownumber > "+start;
				return dao.queryBeanList(beanClass, _sql,args);
			}
			
		};
		
		
		return new PageImpl(engine,pageParam);
		
	}

}
